package com.blog.shiro;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author cgx
 * @Date 2022/1/12 11:48
 */
public class MyAuthenticationFilter extends FormAuthenticationFilter {


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        //获取当前请求的路径
        String basePath = request.getScheme() + "://" + request.getServerName() + ":"  + request.getServerPort()+httpServletRequest.getContextPath();
        //如果request.getHeader("X-Requested-With") 返回的是"XMLHttpRequest"说明就是ajax请求，需要特殊处理 否则直接重定向就可以了
        if("XMLHttpRequest".equals(httpServletRequest.getHeader("X-Requested-With"))){
            //自定义表头
            httpServletResponse.setHeader("REDIRECT", "REDIRECT");
            //重定向的路径
            httpServletResponse.setHeader("CONTEXTPATH", basePath+"/login");
            //设置状态为403
            httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }else{
            httpServletResponse.sendRedirect(basePath + "/login");
        }
        return false;
    }
}
